//
//  SegmentManager.swift
//  forTest
//
//  Created by CarlsonLee on 2020/4/24.
//  Copyright © 2020 CarlsonLee. All rights reserved.
//

import UIKit

protocol SegmentManagerDelegate {
    func segmentTitles() -> [String]
    func segmentControllers() -> [UIViewController]
}

class SegmentManager: UIView, UIScrollViewDelegate {

    var delegate: SegmentManagerDelegate?
    var segment: SegmentView?
    var scroll: UIScrollView?
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    init(frame: CGRect, delegate: SegmentManagerDelegate) {
        super.init(frame: frame)
        self.delegate = delegate
        initSubviews()
    }
    
    func initSubviews() {
        if delegate != nil {
            let titles = (delegate?.segmentTitles())!
            let vcs = (delegate?.segmentControllers())!
            
            //标签栏
            segment = SegmentView(frame: CGRect.zero)
            segment?.normalItem(UIColor.lightGray, 15)
            segment?.selectItem(UIColor.black, 15)
            segment?.itemsArr(titles)
            addSubview(segment!)
            
            //分页内容
            scroll = UIScrollView(frame: CGRect.zero)
            scroll?.showsHorizontalScrollIndicator = false
            scroll?.isPagingEnabled = true
            scroll?.delegate = self
            addSubview(scroll!)
            for i in 0..<vcs.count {
                let vc = vcs[i]
                let view = vc.view!
                var frame = view.frame;
                frame.origin.x = bounds.width*CGFloat(i)
                view.frame = frame
                scroll?.addSubview(view)
//                vc.view.backgroundColor = (i%2)==1 ? UIColor.lightGray:UIColor.white
            }
        }
    }

    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if decelerate {
            let index = Int(scrollView.contentOffset.x/bounds.width)
            segment?.setIndex(index)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x/bounds.width)
        segment?.setIndex(index)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        segment?.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 40)
        scroll?.frame = CGRect(x: 0, y: (segment?.frame.maxY)!, width: bounds.width, height: bounds.height-(segment?.frame.maxY)!)
        scroll?.contentSize = CGSize(width: bounds.width*CGFloat((delegate?.segmentControllers().count)!), height: 0)
        for i in 0..<(scroll?.subviews.count)! {
            let view = scroll?.subviews[i]
            var frame = (view?.frame)!
            frame.origin.x = bounds.width*CGFloat(i)
            view?.frame = frame
        }
    }
}
